package com.jcark.arch.net.utils;

import com.google.gson.Gson;

import java.util.Map;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;


/**
 * AES 是一种可逆加密算法，对用户的敏感信息加密处理 对原始数据进行AES加密后，在进行Base64编码转化；
 */
public class AESOperator {

    private static AESOperator instance = null;
    /*
     * 加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式，key需要为16位。
     */
    private String sKey = "18d0647fa7b47b51";//key，可自行修改
    private String ivParameter = "1120012735479907";//偏移量,可自行修改
//    private String sKey = "5c66ead0a7e18218";//key，可自行修改
//    private String ivParameter = "8083648030027128";//偏移量,可自行修改

    private AESOperator() {

    }


    public static AESOperator getInstance() {
        if (instance == null)
            instance = new AESOperator();
        return instance;
    }

    public String Encrypt(String encData, String secretKey, String vector) throws Exception {

        if (secretKey == null) {
            return null;
        }
        if (secretKey.length() != 16) {
            return null;
        }
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] raw = secretKey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        IvParameterSpec iv = new IvParameterSpec(vector.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(encData.getBytes("utf-8"));
        return new BASE64Encoder().encode(encrypted).replaceAll("\r\n|\r|\n","");// 此处使用BASE64做转码。
    }

    public String encodeBytes(byte[] bytes) {
        StringBuffer strBuf = new StringBuffer();

        for (int i = 0; i < bytes.length; i++) {
            strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
            strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
        }

        return strBuf.toString();
    }

    // 加密
    public String encrypt(String sSrc) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] raw = sKey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        return new BASE64Encoder().encode(encrypted).replaceAll("\r\n|\r|\n","");// 此处使用BASE64做转码。
    }

    public String encryptBySkey(String sSrc, String sKey) throws Exception {
        return Encrypt(sSrc, sKey, this.ivParameter);
    }

    public String encryptByIvKey(String sSrc, String ivKey) throws Exception {
        return Encrypt(sSrc, this.sKey, ivKey);
    }

    public String decryptBySkey(String sSrc, String sKey) throws Exception {
        return decrypt(sSrc, sKey, this.ivParameter);
    }

    public String decryptByIvKey(String sSrc, String ivKey) throws Exception {
        return decrypt(sSrc, this.sKey, ivKey);
    }

    // 解密
    public String decrypt(String sSrc) throws Exception {
        try {
            byte[] raw = sKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            return originalString;
        } catch (Exception ex) {
            return null;
        }
    }

    public String decrypt(String sSrc, String key, String ivs) throws Exception {
        try {
            byte[] raw = key.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivs.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            return originalString;
        } catch (Exception ex) {
            return null;
        }
    }

    public String encryptData(String key, Map<String, Object> map) {
        String dataString = new Gson().toJson(map);
        try {
            return encryptBySkey(dataString, key);
        } catch (Exception e) {
//            e.printStackTrace();
            return "";
        }
    }

    public String encryptData(String key, String json) {
        try {
            return encryptBySkey(json, key);
        } catch (Exception e) {
//            e.printStackTrace();
            return "";
        }

    }

    public String encryptBean(String key, Object obj) {
        String dataString = new Gson().toJson(obj);
        try {
            return encryptBySkey(dataString, key);
        } catch (Exception e) {
//            e.printStackTrace();
            return "";
        }

    }

    /**
     *          * 生成指定位数的随机秘钥
     *          * @param KeyLength
     *          * @return	Keysb
     *          
     */
    public String KeyCreate(int KeyLength) {
        String base = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuffer Keysb = new StringBuffer();
        for (int i = 0; i < KeyLength; i++)    //生成指定位数的随机秘钥字符串
        {
            int number = random.nextInt(base.length());
            Keysb.append(base.charAt(number));
        }
        return Keysb.toString();
    }

}